package com.sc.VenusQueryBeta.ui.fragments.vip.child;

import android.content.Intent;
import android.content.IntentFilter;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.hengjun.kingstar.sdk.base.BasePresenter;
import com.hengjun.kingstar.sdk.base.fragment.BaseMVPCompatFragment;
import com.hengjun.kingstar.sdk.rxbus.RxBus;
import com.hengjun.kingstar.sdk.utils.LogUtil;
import com.hengjun.kingstar.sdk.utils.LogUtils;
import com.hengjun.kingstar.sdk.utils.ResourcesUtils;
import com.hengjun.kingstar.sdk.utils.ScreenUtils;
import com.hengjun.kingstar.sdk.utils.SpUtils;
import com.hengjun.kingstar.sdk.utils.ToastUtils;
import com.sc.VenusQueryBeta.R;
import com.sc.VenusQueryBeta.adapter.account.MsgAdapter;
import com.sc.VenusQueryBeta.constant.Constants;
import com.sc.VenusQueryBeta.constant.event.PusMsgEvent;
import com.sc.VenusQueryBeta.contract.vip.MsgContract;
import com.sc.VenusQueryBeta.global.MyApplication;
import com.sc.VenusQueryBeta.model.UpdateChildMsgEvent;
import com.sc.VenusQueryBeta.model.bean.account.msg.MsgListBean;
import com.sc.VenusQueryBeta.model.bean.login.QueryRegisBean;
import com.sc.VenusQueryBeta.model.bean.login.UsersLoginBean;
import com.sc.VenusQueryBeta.model.sqlite.DataBaseDao;
import com.sc.VenusQueryBeta.model.sqlite.ReadBean;
import com.sc.VenusQueryBeta.presenter.vip.MsgPresenter;
import com.sc.VenusQueryBeta.ui.widgets.SwipeItemLayout;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import io.reactivex.Observer;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;

/**
 * 消息列表页面
 * <p>
 * item_recycle
 */
public class MsgFragment extends BaseMVPCompatFragment<MsgContract.MsgPresenter> implements MsgContract.IMsgView {

    @BindView(R.id.vip_user)
    TextView vipUser;
    @BindView(R.id.ll_errView)
    LinearLayout llErrView;
    @BindView(R.id.rv_vip_list)
    RecyclerView rvVipList;
    @BindView(R.id.tv_empty)
    TextView tvEmpty;
    @BindView(R.id.im_back_sms)
    ImageButton imBackSms;
    @BindView(R.id.rl_top)
    RelativeLayout rlTop;
    private View errorView;
    private UsersLoginBean loginBean;
    private MsgAdapter msgadapter;
    private DataBaseDao dataBaseDao;
    private List<com.sc.VenusQueryBeta.model.sqlite.MsgListBean> msgListBeans;
    private CompositeDisposable compositeDisposable;
    //    private myreceiver recevier;
    private IntentFilter intentFilter;
    private boolean isUpdate = true;
    private ArrayList<com.sc.VenusQueryBeta.model.sqlite.MsgListBean> lastmappleList;
    private ArrayList<ReadBean> lastReadList;
    //    private myreceiver localReceiver;
    private boolean isNew = true;
    private List<com.sc.VenusQueryBeta.model.sqlite.MsgListBean> readBeans;
    private List<ReadBean> readBeans2;
    private String currentSId;
    private List<String> sidlist;

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (compositeDisposable != null) {
            RxBus.rxBusUnbund(compositeDisposable);
        }
    }


    @Override
    public boolean onBackPressedSupport() {
        //通知main
        Intent intentx = new Intent("com.nyl.orderlybroadcast.AnotherBroadcastReceiver");
        intentx.putExtra(Constants.CLOSE_RED, "close");
        //发送本地广播
        LocalBroadcastManager.getInstance(mContext).sendBroadcastSync(intentx);
        pop();
        return true;
    }


    public static MsgFragment newInstance() {
        return new MsgFragment();
    }


    @Override
    public void initData() {
        super.initData();
//        intentFilter = new IntentFilter();
//        intentFilter.addAction("com.nyl.orderlybroadcast.AnotherBroadcastReceiver");
//        localReceiver = new myreceiver();
        //注册本地接收器
//        LocalBroadcastManager.getInstance(mActivity).registerReceiver(localReceiver,intentFilter);
//        reFreshListener();
    }

    @Override
    public void onLazyInitView(@Nullable Bundle savedInstanceState) {
        super.onLazyInitView(savedInstanceState);
        loginBean = SpUtils.getObject(MyApplication.getContext(), UsersLoginBean.class);
        if (loginBean != null) {//已经登录
            dataBaseDao = new DataBaseDao(MyApplication.app, loginBean.getId(), 11);
            showProgressDialog("正在加載");
            mPresenter.getMsgline("", "", 0, loginBean.getId(), "", loginBean.getId());
        }
    }

//    /**
//     * 下拉刷新監聽
//     */
//    private void reFreshListener() {
//        ptrClass.setColorSchemeColors(Color.RED);
//        ptrClass.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
//            @Override
//            public void onRefresh() {
//                ptrClass.postDelayed(new Runnable() {
//                    @Override
//                    public void run() {
//                        if (ptrClass != null) {
//                            ptrClass.setRefreshing(false);
//                        }
////                       if (loginBean != null) {//已经登录
//                        dataBaseDao = new DataBaseDao(MyApplication.app, loginBean.getId(), 11);
//
//                        if (mqueryregisbean != null && mqueryregisbean.getServerSetting() != null) {//有端口
//                            LogUtil.e("" + mqueryregisbean.getServerSetting().getServerAddress() + mqueryregisbean.getServerSetting().
//                                    getServerProject() + mqueryregisbean.getServerSetting().getServerPort());
//                            showProgressDialog("正在加載");
//                            mPresenter.getMsgline(mqueryregisbean.getServerSetting().getServerAddress(), mqueryregisbean.getServerSetting().
//                                    getServerProject(), mqueryregisbean.getServerSetting().getServerPort(), loginBean.getId(), "", loginBean.getId());
//                            LogUtils.e("手机号码=============" + loginBean.getId());
//                        } else {
//                            showProgressDialog("正在加載");
//                            mPresenter.queryRegisterServerSetting(loginBean.getId());//1获取查询注册服务器
//                        }
//
//                    }
//                }, 2000);
//            }
//        });
//    }

    //    @Override
    public void onSupportVisible() {
        super.onSupportVisible();
        RxBus.getInstance().toObservableSticky(PusMsgEvent.class)
                .subscribe(new Observer<PusMsgEvent>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        compositeDisposable.add(d);
                    }

                    @Override
                    public void onNext(PusMsgEvent setShoppingGoodsCount) {
                        if (isUpdate) {
                            isUpdate = false;
                            try {
                                Thread.sleep(1500);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                            showProgressDialog("正在加載");
                            mPresenter.getMsgline("", "", 0, loginBean.getId(), "", loginBean.getId());
                        }


                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    //    public class myreceiver extends BroadcastReceiver {
//        @Override
//        public void onReceive(Context context, Intent intent) {
//            //在这里写上相关的处理代码，一般来说，不要此添加过多的逻辑或者是进行任何的耗时操作
//            //因为广播接收器中是不允许开启多线程的，过久的操作就会出现报错
//            //因此广播接收器更多的是扮演一种打开程序其他组件的角色，比如创建一条状态栏通知，或者启动某个服务
////            ToastUtils.showToast("收到了！");
//            LogUtil.e("收到了！");
//            mPresenter.getMsgline("", "", 0, loginBean.getId(), "", loginBean.getId());
//        }
//    }
    @Override
    public int getLayoutId() {
        return R.layout.activity_msg;
    }

    @Override
    public void initUI(View view, @Nullable Bundle savedInstanceState) {
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(rlTop.getLayoutParams());

        lp.setMargins(0,ScreenUtils.getStatusBarHeight(mContext)+8, 0, 0);

        rlTop.setLayoutParams(lp);
        compositeDisposable = new CompositeDisposable();
        imBackSms.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //通知main
                Intent intentx = new Intent("com.nyl.orderlybroadcast.AnotherBroadcastReceiver");
                intentx.putExtra(Constants.CLOSE_RED, "close");
                //发送本地广播
                LocalBroadcastManager.getInstance(mContext).sendBroadcastSync(intentx);
                pop();
            }
        });
//        reFreshListener();//rv下拉刷新
        if (errorView == null) {
            errorView = ResourcesUtils.inflate(R.layout.view_network_error);
        }
        llErrView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                loginBean = SpUtils.getObject(MyApplication.getContext(), UsersLoginBean.class);
                assert loginBean != null;
                dataBaseDao = new DataBaseDao(MyApplication.app, loginBean.getId(), 11);
                showProgressDialog("正在加載");
                mPresenter.getMsgline("", "", 0, loginBean.getId(), "", loginBean.getId());

                LogUtils.e("手机号码=============" + loginBean.getId());
            }
        });
    }

    @NonNull
    @Override
    public BasePresenter initPresenter() {
        return MsgPresenter.newInstance();
    }

//    @Override
//    public void onResume() {
//        super.onResume();
//        if (loginBean != null) {//已经登录
//            dataBaseDao = new DataBaseDao(MyApplication.app, loginBean.getId(), 11);
//            showProgressDialog("正在加載");
//            mPresenter.getMsgline("", "", 0, loginBean.getId(), "", loginBean.getId());
//        }
//    }

    @Override
    public void showQueryRegisBeanDataSuccess(QueryRegisBean queryRegisBean) {
        if (queryRegisBean != null && queryRegisBean.getServerSetting() != null) {
            hideProgressDialog();
            LogUtils.e("kaska" + queryRegisBean.getServerSetting().getServerAddress());
            SpUtils.putObject(MyApplication.getContext(), queryRegisBean);//保存取查询注册服务器成功返回的数据
            mPresenter.getMsgline(queryRegisBean.getServerSetting().getServerAddress(), queryRegisBean.getServerSetting().
                    getServerProject(), queryRegisBean.getServerSetting().getServerPort(), loginBean.getId(), "", loginBean.getId());
        } else {
            hideProgressDialog();
//            if (tvEmpty != null) {
//                tvEmpty.setVisibility(View.VISIBLE);
//            }
        }
    }

    @Override
    public void showMsgListDataSuccess(MsgListBean msgListBean) {
        hideProgressDialog();
        if (msgListBean != null && msgListBean.getMessageList() != null && msgListBean.getMessageList().size() > 0) {

            isNew = true;
            if (tvEmpty != null && msgListBean.getMessageList().size() != 0) {
//                ptrClass.setVisibility(View.VISIBLE);
                rvVipList.setVisibility(View.VISIBLE);
                tvEmpty.setVisibility(View.GONE);
                llErrView.setVisibility(View.GONE);
            } else {
//                tvEmpty.setVisibility(View.VISIBLE);
            }
            SQLiteDatabase rdb = dataBaseDao.databasehelper.getWritableDatabase();
            rdb.beginTransaction();
            sidlist = new ArrayList<>();

            try {
                //批量处理操作
                for (int i = 0; i < msgListBean.getMessageList().size(); i++) {
                    sidlist.add(String.valueOf(msgListBean.getMessageList().get(i).getSendId()));
                    currentSId = String.valueOf(msgListBean.getMessageList().get(i).getSendId());
                    dataBaseDao.insertInto("", String.valueOf(msgListBean.getMessageList().get(i).getSendClientIndex()), String.valueOf(msgListBean.getMessageList().get(i).getReceiveClientIndex()), msgListBean.getMessageList().get(i).getMessageContent(), msgListBean.getMessageList().get(i).getSendTime(), msgListBean.getMessageList().get(i).getIsRead()
                            , msgListBean.getMessageList().get(i).getSendAreaCode(), msgListBean.getMessageList().get(i).getReceiveAreaCode(), msgListBean.getMessageList().get(i).getSendId(), msgListBean.getMessageList().get(i).getReceiveId(), String.valueOf(msgListBean.getMessageList().get(i).getMessageIndex()), msgListBean.getMessageList().get(i).getVoicePath()
                            , String.valueOf(msgListBean.getMessageList().get(i).getVoiceTime()), "", msgListBean.getMessageList().get(i).getMessageType(), "", "");
                }
                rdb.setTransactionSuccessful(); //设置事务处理成功，不设置会自动回滚不提交
            } catch (Exception e) {
            } finally {
                LogUtil.e("已经插入ss！");
                rdb.endTransaction(); //处理完成
                initRecycleView();
            }

        } else {
            isNew = false;
            initRecycleView();
        }

    }

    @Override
    public void showNetworkError(Throwable throwable) {
        hideProgressDialog();
        llErrView.setVisibility(View.VISIBLE);
    }

    /**
     * 填充账户列表适配器
     */
    private void initRecycleView() {//R.layout.item_tjzx,
        SQLiteDatabase rdb = dataBaseDao.databasehelper.getWritableDatabase();
        rdb.beginTransaction();
        try {
            //批量处理操作
            msgListBeans = dataBaseDao.searchMsg();
            rdb.setTransactionSuccessful(); //设置事务处理成功，不设置会自动回滚不提交
        } catch (Exception e) {

        } finally {
            rdb.endTransaction(); //处理完成
            //分组
            ArrayList<com.sc.VenusQueryBeta.model.sqlite.MsgListBean> group = group(msgListBeans);
            List<com.sc.VenusQueryBeta.model.sqlite.MsgListBean> msgreadBeans = dataBaseDao.searchAllRead();
//            if (isNew) {
//                for (int i = 0; i < group.size(); i++) {
//                    group.get(i).setIsRead("0");
//                }
//                SpUtils.putObject(MyApplication.app, group, new TypeToken<ArrayList<com.sc.VenusQueryBeta.model.sqlite.MsgListBean>>() {
//                }.getType());
//            }
            LogUtil.e("读表大小：" + msgreadBeans.size());
            msgadapter = new MsgAdapter(this.msgListBeans, mContext, dataBaseDao, group, mActivity, msgreadBeans);
            rvVipList.setAdapter(msgadapter);
            rvVipList.setLayoutManager(new LinearLayoutManager(mContext));
            rvVipList.addOnItemTouchListener(new SwipeItemLayout.OnSwipeItemTouchListener(mActivity));
            msgadapter.notifyDataSetChanged();
            if (this.msgListBeans.size() <= 0) {
//                ToastUtils.showToast("msgListBeans.size() <= 0");
//                tvEmpty.setVisibility(View.VISIBLE);
                llErrView.setVisibility(View.GONE);
            } else {
                rvVipList.setVisibility(View.VISIBLE);
                llErrView.setVisibility(View.GONE);
                tvEmpty.setVisibility(View.GONE);
            }
//            rdb.close();
            isUpdate = true;

            Intent intentx = new Intent("com.nyl.orderlybroadcast.AnotherBroadcastReceiver");
            intentx.putExtra(Constants.CLOSE_RED, "close");
            //发送本地广播
            LocalBroadcastManager.getInstance(mContext).sendBroadcastSync(intentx);
        }
        hideProgressDialog();

        msgadapter.setOnCliCkItemListenerr(new MsgAdapter.OnCliCkItemListener() {
            @Override
            public void clickItem(int position, List<com.sc.VenusQueryBeta.model.sqlite.MsgListBean> msgListBeans12) {
                start(MsgChildFragment.newInstance(position, msgListBeans12), 2);
                Intent intentx = new Intent("com.nyl.orderlybroadcast.AnotherBroadcastReceiver");
                intentx.putExtra(Constants.CLOSE_RED, "close");
                //发送本地广播
                LocalBroadcastManager.getInstance(mContext).sendBroadcastSync(intentx);
//                RxBus.getInstance().post(new PusReadNumEvent("close"));//通知红点
//                SpUtils.putBoolean(MyApplication.app, Constants.CLOSE_RED, true);

            }
        });
        if (isUpdate) {
            LogUtil.e("通知了");
            RxBus.getInstance().post(new UpdateChildMsgEvent());//通知msg
        }
    }

    /**
     * 信息表分组
     *
     * @param msgListBeans
     * @return
     */
    private ArrayList<com.sc.VenusQueryBeta.model.sqlite.MsgListBean> group(List<com.sc.VenusQueryBeta.model.sqlite.MsgListBean> msgListBeans) {
        Map<String, List<com.sc.VenusQueryBeta.model.sqlite.MsgListBean>> listMap = new HashMap<>();
        for (com.sc.VenusQueryBeta.model.sqlite.MsgListBean bean : msgListBeans) {
            String key = bean.getSendId();
            Log.e("key", "key=" + key);
            if (listMap.containsKey(key)) {
                listMap.get(key).add(bean);
            } else {
                List<com.sc.VenusQueryBeta.model.sqlite.MsgListBean> mappleList1 = new ArrayList<>();//存放apple对象集合
                mappleList1.add(bean);
                listMap.put(key, mappleList1);
            }
        }
        Log.e("map", "size=" + listMap.size());
        lastmappleList = new ArrayList<>();
        for (String id : listMap.keySet()) {
            Log.e("map", "name=" + listMap.get(id).size());
            //存放apple对象集合 可以判断循环标志
            lastmappleList.add(listMap.get(id).get(listMap.get(id).size() - 1));
//            for (int i=0;i<listMap.get(id).size();i++) {
//                lastmappleList.add(listMap.get(id).get(i));
//            }
        }

        SQLiteDatabase rdb = dataBaseDao.databasehelper.getWritableDatabase();
        rdb.beginTransaction();
        try {
            //批量处理操作
            if (isNew) {
                isNew = false;
                //设置未读
                LogUtil.e("lastmappleLis大小：" + lastmappleList.size());
//                for (int i = 0; i < lastmappleList.size(); i++) {
//                    LogUtil.e("sas=" + String.valueOf(sidlist.get(i)));
                for (int i = 0; i < sidlist.size(); i++) {
                    LogUtil.e("newUId" + sidlist.get(i));
                    dataBaseDao.insertRead("", String.valueOf(lastmappleList.get(i).getSendClientIndex()), String.valueOf(lastmappleList.get(i).getReceiveClientIndex()), lastmappleList.get(i).getMessageContent(), lastmappleList.get(i).getSendTime(), lastmappleList.get(i).getIsRead()
                            , lastmappleList.get(i).getSendAreaCode(), lastmappleList.get(i).getReceiveAreaCode(), sidlist.get(i), lastmappleList.get(i).getReceiveId(), String.valueOf(lastmappleList.get(i).getMessageIndex()), lastmappleList.get(i).getVoicePath()
                            , String.valueOf(lastmappleList.get(i).getVoiceTime()), "", lastmappleList.get(i).getMessageType(), "", "");
                }
//                }
            } else {
                LogUtil.e("沒有新的通知來，不插入read表");
            }

            rdb.setTransactionSuccessful(); //设置事务处理成功，不设置会自动回滚不提交
        } catch (Exception e) {
        } finally {
            LogUtil.e("已经插入read！");
            rdb.endTransaction(); //处理完成
//            queryFinal();
        }
        return lastmappleList;
    }

    private void queryFinal() {
        SQLiteDatabase rdb = dataBaseDao.databasehelper.getWritableDatabase();
        rdb.beginTransaction();
        try {
            //批量处理操作
            readBeans = dataBaseDao.searchAllRead();
            LogUtil.e("read 表的大小" + readBeans.size());
            for (int i = 0; i < readBeans.size(); i++) {
                LogUtil.e("查詢時候的isRead=" + readBeans.get(i).getIsRead());
            }
            rdb.setTransactionSuccessful(); //设置事务处理成功，不设置会自动回滚不提交
        } catch (Exception e) {
            LogUtil.e("Exception:" + e.getMessage());
        } finally {
            rdb.endTransaction(); //处理完成
//            groupRead(readBeans);
        }
    }

    /**
     * 分組閱讀表
     *
     * @param readBeans
     * @return
     */
    private List<ReadBean> groupRead(List<ReadBean> readBeans) {
        Map<String, List<ReadBean>> listMap = new HashMap<>();
        for (ReadBean bean : readBeans) {
            String key = bean.getSendId();
            Log.e("readkey", "readkey=" + key);
            if (listMap.containsKey(key)) {
                listMap.get(key).add(bean);
            } else {
                List<ReadBean> mappleList1 = new ArrayList<>();//存放apple对象集合
                mappleList1.add(bean);
                listMap.put(key, mappleList1);
            }
        }
        Log.e("map", "size=" + listMap.size());
        lastReadList = new ArrayList<>();
        for (String id : listMap.keySet()) {
            Log.e("map", "name=" + listMap.get(id).size());
            //存放apple对象集合 可以判断循环标志
            lastReadList.add(listMap.get(id).get(listMap.get(id).size() - 1));
//            for (int i=0;i<listMap.get(id).size();i++) {
//                lastmappleList.add(listMap.get(id).get(i));
//            }
        }
        return lastReadList;
    }

}
